/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.struts;

import com.cashmate.hibernate.dao.EmployeeDAO;
import com.cashmate.hibernate.dao.UsertypeEmployeeDAO;
import com.cashmate.hibernate.pojo.Branches;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.hibernate.pojo.Usertypes;
import com.cashmate.utilities.Utils;
import com.opensymphony.xwork2.ActionSupport;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;

/**
 *
 * @author Dine
 */
@InterceptorRef(value = "loginDefault")
public class LoginAuthentication extends ActionSupport {

    private static final Logger logger = Logger.getLogger(LoginAuthentication.class);
    private static final EmployeeDAO emp = (EmployeeDAO) ServletActionContext.getServletContext().getAttribute("employeeDAO");
    private static final UsertypeEmployeeDAO utypeEmp = (UsertypeEmployeeDAO) ServletActionContext.getServletContext().getAttribute("useremployeeDAO");
    public String idnumber, employeePassword;
    private InputStream inputStream;

    public void setIdnumber(String idnumber) {
        this.idnumber = idnumber;
    }

    public void setEmployeePassword(String employeePassword) {
        this.employeePassword = employeePassword;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    @Action(value = "/login-authentication", results = {
        @Result(name = "success", type = "stream", params = {"inputName", "inputStream", "contentType", "text/html"})
    })
    @Override
    public String execute() {
        try {
            logger.info(idnumber + " is potentially signing-in in the system.");
            if (Utils.isValid(idnumber, 6, 11) && Utils.isDigit(idnumber)) {
                if (!Utils.isValid(employeePassword, 6, 12)) {
                    inputStream = new StringBufferInputStream(setErrorScript("employeePassword", 1));
                } else {
                    String empStatus = emp.validateEmployee(idnumber, employeePassword);
                    if (empStatus.equals("none")) {
                        inputStream = new StringBufferInputStream(setErrorScript("employeeId", 2));
                        logger.info("Employee " + idnumber + " is denied access to the system due to false credentials.");
                    } else if (empStatus.equals("incorrect")) {
                        inputStream = new StringBufferInputStream(setErrorScript("employeePassword", 2));
                        logger.info("Employee " + idnumber + " is denied access to the system due to false credentials.");
                    } else if (empStatus.equals("ok")) {
                        Employees e = emp.getByIdNumber(idnumber);
                        Usertypes ut = utypeEmp.get(e.getUsertypeEmployeeid()).getUsertypes();
                        Branches b = e.getBranches();
                        HttpSession session = ServletActionContext.getRequest().getSession(true);
                        session.setAttribute("auth", true);
                        session.setAttribute("branch", b);
                        session.setAttribute("employee", e);
                        session.setAttribute("usertype", ut);

                        Map<Employees, HttpSession> USERS = (HashMap<Employees, HttpSession>) ServletActionContext.getServletContext().getAttribute("USERS");
                        if (!USERS.containsKey(e)) {
                            USERS.put(e, session);
                            ServletActionContext.getServletContext().setAttribute("USERS", USERS);
                        }


                        logger.info("Employee " + idnumber + " logged in as " + ut.getType() + " in " + b.getBranchname() + " branch.");
                        if (ut.getType().equals("Administrator")) {
                            inputStream = new StringBufferInputStream("<script type=\"text/javascript\">window.location = \"admin.jsp\"</script>");
                        } else {
                            inputStream = new StringBufferInputStream("<script type=\"text/javascript\">window.location = \"home.jsp\"</script>");
                        }
                    }
                }
            } else {
                logger.info("Employee " + idnumber + " is denied access to the system due to false credentials.");
                inputStream = new StringBufferInputStream(setErrorScript("employeeId", 1));
            }

        } catch (Exception e) {
            logger.fatal(e.getLocalizedMessage(), e);
            addActionError(e.getLocalizedMessage());
            return ERROR;
        } finally {
            try {
                EmployeeDAO.close();
                UsertypeEmployeeDAO.close();
            } catch (Exception e) {
                logger.fatal(e.getMessage(), e);
            }
        }
        return SUCCESS;
    }

    public String setErrorScript(String field, int errorType) {
        String toggleError = "<script type=\"text/javascript\">$('#formResult').addClass('ui-state-error').removeClass('ui-state-highlight');$('#brLogForm').show();";
        String errorMessage = "<p style=\"text-align:center;\"><span class=\"ui-icon ui-icon-alert\"></span>";
        if (field.equals("employeeId")) {
            toggleError += "setError(\"employeeId\");</script>";
            switch (errorType) {
                case 1:
                    errorMessage += "Please enter a valid <strong>ID number greater than or equal to 6 digits.</strong>";
                    break;
                case 2:
                    errorMessage += "Sorry. <strong>ID Number does not exist</strong>.";
                    break;
            }
        } else if (field.equals("employeePassword")) {
            toggleError += "setError(\"employeePassword\");</script>";
            switch (errorType) {
                case 1:
                    errorMessage += "Please enter a valid <strong>Employee Password between 6 to 12 characters.</strong>";
                    break;
                case 2:
                    errorMessage += "Sorry. <strong>Incorrect Employee Password.</strong>";
                    break;
            }
        }
        return toggleError + errorMessage + "</p>";
    }
}
